import { ShapeBaseInfoApi, ShapeBaseStyleApi } from './api'
interface Events {
	[type: string]: Function[]
}
class Shape {
	index: number
	events: Events
	info: ShapeBaseInfoApi
	style: ShapeBaseStyleApi
	constructor(info: ShapeBaseInfoApi, style?: ShapeBaseStyleApi) {
		this.index = 0
		this.events = {}
		this.info = info
		this.style = Object.assign(
			{},
			{
				background: 'transparent',
				border: 'black',
				borderWidth: 2,
				zIndex: 0,
			},
			style
		)
	}
	isInside(dx: number, dy: number): boolean {
		const { x: left, y: top, width, height } = this.info

		// console.log(left, top, width, height)
		return dx >= left && dx <= left + width && dy >= top && dy <= top + height
	}
	add() {
		
	}
	// 监听事件
	on(type: string, listener: Function): void {
		if (!this.events[type]) {
			this.events[type] = [listener]
		} else {
			this.events[type].push(listener)
		}
	}
	emit(type: string, ...args: any[]): void {
		this.events[type].forEach(listener => listener(...args))
	}
	draw(ctx: CanvasRenderingContext2D): void {}
}

class Rect extends Shape {
	constructor(info: ShapeBaseInfoApi, style?: ShapeBaseStyleApi) {
		super(info, style)
	}
	draw(ctx: CanvasRenderingContext2D) {
		const { x, y, width, height } = this.info
		ctx.beginPath()
		this.setStyle(ctx)
		ctx.save()
		ctx.translate(x + width / 2, y + height / 2)
		ctx.rect(-width / 2, -height / 2, width, height)
		ctx.restore()
		ctx.fill()
		ctx.stroke()
		ctx.closePath()
	}
	setStyle(ctx: CanvasRenderingContext2D) {
		ctx.fillStyle = this.style.background || 'transparent'
	}
}
class RoundRect extends Shape {
	constructor(info: ShapeBaseInfoApi, style?: ShapeBaseStyleApi) {
		super(info, style)
	}
}

export { Shape, Rect, RoundRect }
